<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-tabs v-model="activeName" @tab-click="handleClick">
				<el-tab-pane label="二手仪器" name="0"></el-tab-pane>
				<el-tab-pane label="新仪器" name="1"></el-tab-pane>
			</el-tabs>
			<el-row class="ml10" v-show="showSearch">
				<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef">
					<el-form-item label="产品名称" prop="productName">
						<el-input placeholder="请输入 产品名称" style="max-width: 180px" v-model="state.queryForm.productName" clearable />
					</el-form-item>
					<el-form-item label="产品分类" prop="categoryId">
						<el-select v-model="state.queryForm.categoryId" placeholder="请选择 产品分类" @change="handleCategoryChange" clearable>
							<el-option v-for="item in productTypeData" :key="item.id" :label="item.categoryName" :value="item.id" />
						</el-select>
						<!-- <el-input placeholder="请输入 产品分类" style="max-width: 180px" v-model="state.queryForm.categoryId" /> -->
					</el-form-item>

					<el-form-item label="关键字" prop="key">
						<el-input placeholder="产品名称/产品分类/产品型号/产品品牌" style="width: 300px" v-model="state.queryForm.key" clearable />
					</el-form-item>
					<el-form-item>
						<el-button @click="getDataList" icon="search" type="primary">
							{{ $t('common.queryBtn') }}
						</el-button>
						<el-button @click="resetQuery" icon="Refresh">{{ $t('common.resetBtn') }}</el-button>
					</el-form-item>
				</el-form>
			</el-row>
			<el-row>
				<div class="mb8" style="width: 100%">
					<el-button @click="formDialogRef.openDialog('', activeName)" class="ml10" icon="folder-add" type="primary" v-auth="'sys_post_add'">
						{{ $t('common.addBtn') }}
					</el-button>
					<el-button plain :disabled="multiple" @click="handleDelete(selectObjs)" class="ml10" icon="Delete" type="primary" v-auth="'sys_post_del'">
						{{ $t('common.delBtn') }}
					</el-button>
					<right-toolbar
						:export="'false'"
						@exportExcel="exportExcel"
						@queryTable="getDataList"
						class="ml10"
						style="float: right; margin-right: 20px"
						v-model:showSearch="showSearch"
					></right-toolbar>
				</div>
			</el-row>
			<el-table
				:data="state.dataList"
				@selection-change="handleSelectionChange"
				style="width: 100%"
				v-loading="state.loading"
				border
				:cell-style="tableStyle?.cellStyle"
				:header-cell-style="tableStyle?.headerCellStyle"
			>
				<el-table-column align="center" type="selection" width="40" />
				<el-table-column :label="t('post.index')" type="index" width="60" />
				<!-- other.addUnit(props.width) -->
				<el-table-column label="产品名称" prop="productName" show-overflow-tooltip />
				<el-table-column label="产品分类" prop="categoryId" show-overflow-tooltip>
					<template #default="scope">
						<span>{{ scope.row.categoryName || getLabel(productTypeData, 'id', scope.row.categoryId, 'categoryName') }} </span>
					</template>
				</el-table-column>
				<el-table-column label="产品型号" prop="model" show-overflow-tooltip />
				<el-table-column label="产品品牌" prop="brand" show-overflow-tooltip />
				<el-table-column label="产品频率" prop="frequency" show-overflow-tooltip />
				<el-table-column label="产品选件" prop="accessories" show-overflow-tooltip />
				<el-table-column label="产品图片" prop="images" show-overflow-tooltip>
					<template #default="scope">
						<img v-if="scope.row.images" style="width: 100px; height: 60px" :src="`${baseUrl}${scope.row.images.split(',')[0]}`" alt="" />
					</template>
				</el-table-column>
				<el-table-column :label="$t('common.action')" width="200">
					<template #default="scope">
						<el-button icon="edit-pen" @click="formDialogRef.openDialog(scope.row.id)" text type="primary" v-auth="'sys_post_edit'"
							>{{ $t('common.editBtn') }}
						</el-button>

						<el-button icon="delete" @click="handleDelete([scope.row.id])" text type="primary" v-auth="'sys_post_del'"
							>{{ $t('common.delBtn') }}
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<pagination @current-change="currentChangeHandle" @size-change="sizeChangeHandle" v-bind="state.pagination" />
		</div>

		<!-- 编辑、新增  -->
		<form-dialog @refresh="getDataList()" ref="formDialogRef" />
	</div>
</template>

<script lang="ts" name="systemPost" setup>
import { BasicTableProps, useTable } from '/@/hooks/table';
import { fetchList, delObjs } from '/@/api/qytest/sysProduct';
import { getProductCategory } from '/@/api/qytest/sysProductCategory';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { reactive, onMounted } from 'vue';
import type { TabsPaneContext } from 'element-plus';
import { useI18n } from 'vue-i18n';
import other from '/@/utils/other';

const baseUrl = import.meta.env.VITE_ADMIN_PROXY_PATH;
// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
const { t } = useI18n();

// 定义变量内容
const activeName = ref('0');
const formDialogRef = ref();
// 搜索变量
const queryRef = ref();
const showSearch = ref(true);
// 多选变量
const selectObjs = ref([]) as any;
const multiple = ref(true);
const productTypeData = ref([]) as any;

onMounted(() => {
	getProductTypeData();
});
const handleClick = (tab: TabsPaneContext, event: Event) => {
	state.queryForm.isNewProduct = tab.props.name;
	getDataList();
};
const handleCategoryChange = (val: string) => {
	state.queryForm.categoryName = other.findLabelByKey(productTypeData.value, 'id', val, 'categoryName');
};
const getLabel = (data: any, key: string, value: string, label: string) => {
	return other.findLabelByKey(data, key, value, label);
};
const getProductTypeData = () => {
	getProductCategory({ current: -1 })
		.then((res: any) => {
			productTypeData.value = res.data.records || [];
		})
		.finally(() => {});
};
const state: BasicTableProps = reactive<BasicTableProps>({
	queryForm: {
		isNewProduct: activeName.value,
		categoryName: '',
	},
	pageList: fetchList,
});

//  table hook
const { getDataList, currentChangeHandle, sizeChangeHandle, downBlobFile, tableStyle } = useTable(state);

// 清空搜索条件
const resetQuery = () => {
	state.queryForm.categoryName = '';
	queryRef.value.resetFields();
	getDataList();
};

// 导出excel
const exportExcel = () => {
	downBlobFile('/admin/post/export', state.queryForm, 'post.xlsx');
};

// 多选事件
const handleSelectionChange = (objs: { postId: string }[]) => {
	selectObjs.value = objs.map(({ postId }) => postId);
	multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
	try {
		await useMessageBox().confirm(t('common.delConfirmText'));
	} catch {
		return;
	}

	try {
		await delObjs(ids);
		getDataList();
		useMessage().success(t('common.delSuccessText'));
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
</script>
